/*
 * #%L
 * Tools
 * %%
 * Copyright (C) 2011 Ractoc.com
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */
package com.ractoc.tools.logging;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.logging.Handler;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

/**
 * Enables logging java.util.loggin log messages through Log4J. This class copies
 * the log4j configuration into java.util.logging where appropriate.
 * 
 * To implement this in your own code use the followin snippet to configure the handler:
 * 
 * <pre>
   ConfigureJulFromLog4j cjfl4j = new ConfigureJulFromLog4j();
        try {
            cjfl4j.configure();
        } catch (FileNotFoundException ex) {
            logger.error("unable to configure JUL form Log4J. JUL messages will not be logged.", ex);
        } catch (IOException ex) {
            logger.error("unable to configure JUL form Log4J. JUL messages will not be logged.", ex);
        }
   </pre>   
 * 
 * @author ractoc
 */
public class ConfigureJulFromLog4j {

    private Handler activeHandler;
    private List<Handler> oldHandlers = new ArrayList<Handler>();
    private java.util.logging.Level handlerLevel = java.util.logging.Level.ALL;
    private java.util.logging.Level rootLevel = java.util.logging.Level.INFO;

    public void configure() throws FileNotFoundException, IOException {

        JuliToLog4jHandler.getTargetLogger(JuliToLog4jHandler.class).info("start(): Redirecting java.util.logging to Log4J...");

        java.util.logging.Logger rootLogger = java.util.logging.LogManager.getLogManager().getLogger("");
        // remove old handlers            
        for (Handler handler : rootLogger.getHandlers()) {
            oldHandlers.add(handler);
            rootLogger.removeHandler(handler);
        }
        
        // add our own
        activeHandler = new JuliToLog4jHandler();            
        activeHandler.setLevel(handlerLevel);            
        rootLogger.addHandler(activeHandler);            
        rootLogger.setLevel(rootLevel);            
        // done, let's check it right away!!!             
        java.util.logging.Logger.getLogger(JuliToLog4jHandler.class.getName()).info("started: sending JDK log messages to Log4J");
        Logger.getLogger(JuliToLog4jHandler.class.getName()).info("Setting up the Log4J loggers in the JDK logging.");

        Enumeration loggers = LogManager.getCurrentLoggers();
        while (loggers.hasMoreElements()) {
            Logger l = (Logger) loggers.nextElement();
            String loggerName = l.getName();
            java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger(loggerName);
            if (Level.ERROR == l.getLevel()) {
                julLogger.setLevel(java.util.logging.Level.SEVERE);
            } else if (Level.WARN == l.getLevel()) {
                julLogger.setLevel(java.util.logging.Level.WARNING);
            } else if (Level.INFO == l.getLevel()) {
                julLogger.setLevel(java.util.logging.Level.INFO);
            } else if (Level.DEBUG == l.getLevel()) {
                julLogger.setLevel(java.util.logging.Level.FINE);
            } else if (Level.OFF == l.getLevel()) {
                julLogger.setLevel(java.util.logging.Level.OFF);
            }
            java.util.logging.LogManager.getLogManager().addLogger(julLogger);
        }
    }
}
